from __future__ import absolute_import
from lviewer.util import events

try:
    import pyinotify
except ImportError:
    pyinotify = None
    valid = False
else:
    valid = True

# don't try to make this class
# if we cannot import from pyinotify
if valid:
    class INotifyFileChangeMonitor( pyinotify.ProcessEvent ):

        def __init__(self, folder):
            self.folder = folder
            self.on_change = events.Event()

            self.wm = pyinotify.WatchManager()
            self.notifier = pyinotify.ThreadedNotifier(self.wm, self)
            self.notifier.start()
            self.wdd = self.wm.add_watch(self.folder,
                pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE, rec = True,
                auto_add = True)

        def stop(self):
            self.wm.rm_watch(self.wdd.values())
            self.notifier.stop()
       
        def process_default(self, event):
            self.on_change.fire()
